<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片模块 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary"
                     @click="addRole">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList"
                border>
        <!-- 展开模块 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row v-for="(item1,i1) in scope.row.children"
                    :key="item1.id"
                    :class="['bborder',i1==0?'tborder ':'','vcenter']">
              <!-- 一级的渲染 -->
              <el-col :span="8">
                <el-tag closable
                        type="danger"
                        @close="removeRoles(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级三级的渲染 -->
              <el-col :span="16">
                <el-row v-for="(item2,i2) in item1.children"
                        :key="item2.id"
                        :class="[i2==0?'':'tborder','lborder']">
                  <el-col :span="9">
                    <el-tag closable
                            type="warning"
                            @close="removeRoles(scope.row,item2.id)">
                      {{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="15">
                    <el-tag closable
                            type="success"
                            v-for="item3 in item2.children"
                            :key="item3.id"
                            @close="removeRoles(scope.row,item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 编号小模块 -->
        <el-table-column type="index"></el-table-column>
        <!-- 角色名称 -->
        <el-table-column label="角色名称"
                         prop="roleName"></el-table-column>
        <!-- 角色描述 -->
        <el-table-column label="角色描述"
                         prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <!-- 操作小模块 -->
          <template slot-scope="scope">
            <el-button type="primary"
                       size="mini"
                       icon="el-icon-edit"
                       @click="editCole(scope)">编辑</el-button>
            <el-button type="danger"
                       size="mini"
                       icon="el-icon-delete"
                       @click="deleteRole(scope.row)">删除</el-button>
            <el-button type="warning"
                       size="mini"
                       icon="el-icon-setting"
                       @click="setRolesDialogVisibile(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限 对话框 -->
    <el-dialog title="提示"
               :visible.sync="rolesDialogVisible"
               width="50%"
               @close="closeRolesDialog">
      <!-- 权限的树形结构 -->
      <el-tree :data="rightsList"
               :props="defaultProps"
               show-checkbox
               node-key="id"
               :default-checked-keys="defCheckedKeys"
               default-expand-all
               ref="rolesRef">
      </el-tree>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="rolesDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="confirmDialogVisible">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色"
               :visible.sync="addRolesRialogVisible"
               width="50%"
               @close="closeAddDialog">
      <!-- 提交的表单区域 -->
      <el-form :model="addRoleRequest"
               :rules="addRoleRules"
               ref="addRoleRef"
               label-width="100px"
               class="demo-ruleForm">

        <el-form-item label="角色名称"
                      prop="roleName">
          <el-input v-model="addRoleRequest.roleName"></el-input>
        </el-form-item>

        <el-form-item label="角色描述">
          <el-input v-model="addRoleRequest.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addRolesRialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addroleFrom">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑角色"
               :visible.sync="editRolesRialogVisible"
               width="50%"
               @close="closeeditDialog">
      <!-- 提交的表单区域 -->
      <el-form :model="editRoleRequest"
               :rules="addRoleRules"
               ref="editRoleRef"
               label-width="100px"
               class="demo-ruleForm">
        <el-form-item label="角色ID"
                      prop="roleID">
          <el-input v-model="editRoleRequest.id"
                    disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名称"
                      prop="roleName">
          <el-input v-model="editRoleRequest.roleName"></el-input>
        </el-form-item>

        <el-form-item label="角色描述">
          <el-input v-model="editRoleRequest.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editRolesRialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="editroleFrom">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 获取的角色列表
      rolesList: [],
      // 控制分配权限对话框
      rolesDialogVisible: false,
      // 获取权限列表
      rightsList: [],
      // 树形空间
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认被勾选的值
      defCheckedKeys: [],
      // 点击分配权限,保存角色ID
      rolesID: '',
      // 控制添加角色对话框的显示隐藏
      addRolesRialogVisible: false,
      // 添加角色的请求
      addRoleRequest: {},
      // 添加角色对话框的验证规则
      addRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ]
      },
      // 编辑角色的请求
      editRoleRequest: {},
      // 控制编辑对话框的显示隐藏
      editRolesRialogVisible: false
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      this.rolesList = res.data
    },
    // 删除角色指定权限
    async removeRoles (roles, id) {
      const i = await this.$confirm('此操作将永久该特权, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (i === 'cancel') {
        return this.$message.info('已取消')
      }
      const { data: res } = await this.$http.delete(`roles/${roles.id}/rights/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('修改失败')
      }
      roles.children = res.data
    },
    // 分配权限
    async setRolesDialogVisibile (roles) {
      this.rolesID = roles.id
      const { data: res } = await this.$http.get('rights/tree')
      this.getRightsID(roles, this.defCheckedKeys)
      this.rightsList = res.data
      this.rolesDialogVisible = true
    },
    // 递归遍历角色信息获取已拥有权限ID
    getRightsID (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getRightsID(item, arr)
      })
    },
    // 关闭分配权限对话框
    closeRolesDialog () {
      this.rolesID = ''
      this.defCheckedKeys = []
    },
    // 确任提交修改分配的特权
    async confirmDialogVisible () {
      const keys = [...this.$refs.rolesRef.getCheckedKeys(), ...this.$refs.rolesRef.getHalfCheckedKeys()]
      console.log(this.rolesID)
      console.log(keys.join(','))
      var keysId = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.rolesID}/rights`, { rids: keysId })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('分配失败')
      }
      this.getRolesList()
      console.log(this.rolesList)

      this.rolesDialogVisible = false
      this.$message.success('分配成功')
    },
    // 添加角色按钮
    addRole () {
      this.addRolesRialogVisible = true
    },
    // 确任添加角色
    addroleFrom () {
      this.$refs.addRoleRef.validate(async (valid) => {
        if (!valid) return ''
        const { data: res } = await this.$http.post('roles', {
          roleName: this.addRoleRequest.roleName,
          roleDesc: this.addRoleRequest.roleDesc
        })
        if (res.meta.status !== 200) {
          this.$message.error('添加角色失败')
        }
        this.$message.success('添加角色成功')
        this.getRolesList()
        this.addRolesRialogVisible = false
      })
    },
    // 监听添加对话框的关闭
    closeAddDialog () {
      this.addRoleRequest.roleDesc = ''
      this.$refs.addRoleRef.resetFields()
    },
    // 点击编辑按钮
    editCole (role) {
      this.editRoleRequest = Object.assign({}, role)
      this.editRolesRialogVisible = true
    },
    // 确任编辑角色
    editroleFrom () {
      this.$refs.editRoleRef.validate(async valid => {
        if (!valid) return ''
        const { data: res } = await this.$http.put('roles/' + this.editRoleRequest.id, {
          roleName: this.editRoleRequest.roleName,
          roleDesc: this.editRoleRequest.roleDesc
        })
        if (res.meta.status !== 200) return this.$message.error('编辑角色失败')
        this.$message.success('编辑角色成功')
        this.getRolesList()
        this.editRolesRialogVisible = false
      })
    },
    // 监听编辑角色对话框的关闭事件
    closeeditDialog () {
      this.editRoleRequest = {}
      this.$refs.editRoleRef.resetFields()
    },
    // 删除角色
    deleteRole (role) {
      this.$confirm('你确定要删除当前角色嘛？', '删除角色', {
        confirmButtonText: '确定',
        callback: async action => {
          if (action === 'cancel') {
            this.$message.info('已取消删除')
          } else if (action === 'confirm') {
            const { data: res } = await this.$http.delete('roles/' + role.id)
            if (res.meta.status !== 200) return this.$message.error('删除角色失败')
            this.$message.success('删除角色成功')
            this.getRolesList()
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 20px;
}
.el-tag {
  margin: 20px;
}

.bborder {
  border-bottom: 1px solid #eee;
}
.tborder {
  border-top: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
